package com.atguigu.edu.realtime.dwd.db.split.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.realtime.common.bean.TableProcessDwd;
import com.atguigu.edu.realtime.common.base.BaseApp;
import com.atguigu.edu.realtime.common.constant.Constant;
import com.atguigu.edu.realtime.common.util.FlinkSinkUtil;
import com.atguigu.edu.realtime.common.util.FlinkSourceUtil;
import com.atguigu.edu.realtime.dwd.db.split.function.BaseDbTableProcessFunction;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @author Felix
 * @date 2024/11/04
 * 事实表动态分流
 * 需要启动的进程
 *      zk、kafka、maxwell、DwdBaseDb
 */
public class DwdBaseDb extends BaseApp {
    // TODO: 2024/11/14 从 kafka topic_db 中读取数据,并 经过handle 处理，最后写入 kafka dwd层的 主要题中
    public static void main(String[] args) {
        new DwdBaseDb().start(10019,
                4,
                "dwd_base_db",
                Constant.TOPIC_DB
        );

    }
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> kafkaStrDS) {
        //TODO 1.对流中数据进行类型转换并进行简单的ETL jsonStr->jsonObj
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaStrDS.process(
                new ProcessFunction<String, JSONObject>() {
                    @Override
                    public void processElement(String jsonStr, ProcessFunction<String, JSONObject>.Context ctx, Collector<JSONObject> out) throws Exception {
                        try {
                            JSONObject jsonObj = JSON.parseObject(jsonStr);
                            String type = jsonObj.getString("type");
                            if (!type.startsWith("bootstrap-")) {
                                out.collect(jsonObj);
                            }
                        } catch (Exception e) {
                            System.out.println("~~~不是一个标准的json~~~");
                        }
                    }
                }
        );
        // jsonObjDS.print();

        //TODO 2.使用FlinkCDC读取配置表的配置信息
        //2.1 创建MySqlSource对象
        MySqlSource<String> mySqlSource = FlinkSourceUtil.getMySqlSource("edu_config", "table_process_dwd");
        //2.2 读取数据 封装为流
        DataStreamSource<String> mysqlStrDS
                = env.fromSource(mySqlSource, WatermarkStrategy.noWatermarks(), "mysql_source").setParallelism(1);
        // "op":"r": {"before":null,
        //           "after":{"source_table":"user_info","source_type":"insert","sink_table":"dwd_user_register","sink_columns":"id,login_name,nick_name,passwd,real_name,phone_num,email,head_img,user_level,birthday,gender,create_time,operate_time,status"},"source":{"version":"1.9.7.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":0,"snapshot":"false","db":"edu_config","sequence":null,"table":"table_process_dwd","server_id":0,"gtid":null,"file":"","pos":0,"row":0,"thread":null,"query":null},"ts_ms":1731568883070,"transaction":null}
        // mysqlStrDS.print();

        //2.3 对配置流数据进行类型转换  jsonStr->jsonObj->实体类对象
        SingleOutputStreamOperator<TableProcessDwd> tpDS = mysqlStrDS.map(
                new MapFunction<String, TableProcessDwd>() {
                    @Override
                    public TableProcessDwd map(String jsonStr) throws Exception {
                        //为了处理方便，先将jsonStr转换为jsonObj
                        JSONObject jsonObj = JSON.parseObject(jsonStr);
                        //获取对配置表进行的操作的类型
                        String op = jsonObj.getString("op");
                        TableProcessDwd tableProcessDwd = null;
                        // TODO: 2024/11/14  将 jsonObj -> tableProcessDwd ( op=d,jsonObj['before']->tableProcessDwd; else jsonObj['after']->tableProcessDwd)
                        if ("d".equals(op)) {
                            //说明从配置表中删除了一条配置信息，应该从before属性中获取删除前的配置
                            /**
                             * 根据键获取并转换对象
                             * 该方法用于从一个映射（map）中根据给定的键获取对象，并将其转换为指定类型的JavaBean
                             *
                             * @param key 键，用于从映射中获取对象
                             * @param clazz 指定类型，将获取到的对象转换为该类型的JavaBean
                             * @param <T> 泛型参数，表示返回值的类型
                             * @return 转换后的指定类型的JavaBean对象
                             */
                            tableProcessDwd = jsonObj.getObject("before", TableProcessDwd.class);
                        } else {
                            //说明对配置表进行读取、更新、添加操作，应该从after属性中获取最新的配置
                            tableProcessDwd = jsonObj.getObject("after", TableProcessDwd.class);
                        }
                        //补充操作类型  因为后面需要根据操作类型来判断是添加还是更新还是删除
                        tableProcessDwd.setOp(op);
                        return tableProcessDwd;
                    }
                }
        ).setParallelism(1);
        /**
         * op=r: TableProcessDwd(sourceTable=user_info, sourceType=insert, sinkTable=dwd_user_register, sinkColumns=id,login_name,nick_name,passwd,real_name,phone_num,email,head_img,user_level,birthday,gender,create_time,operate_time,status, op=r)
         */
        // tpDS.print("tpDS");

        //TODO 3.对配置流进行广播---broadcast
        MapStateDescriptor<String, TableProcessDwd> mapStateDescriptor
                = new MapStateDescriptor<String, TableProcessDwd>("mapStateDescriptor", String.class, TableProcessDwd.class);
        BroadcastStream<TableProcessDwd> broadcastDS = tpDS.broadcast(mapStateDescriptor);
        //TODO 4.将主流业务数据和广播流中的配置信息进行关联---connect
        BroadcastConnectedStream<JSONObject, TableProcessDwd> connectDS = jsonObjDS.connect(broadcastDS);

        //TODO 5.对关联后的数据进行处理---process
        SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDwd>> realDS = connectDS.process(
                new BaseDbTableProcessFunction(mapStateDescriptor)
        );

         realDS.print("realDS");
        /**
         * Tuple2<JSONObject, TableProcessDwd>:
         *        ({"birthday":"1971-08-13","create_time":"2024-11-13 00:00:00","login_name":"u0v2iyspathd","user_level":"2","phone_num":"13843486266","id":1351,"email":"u0v2iyspathd@0355.net","ts":1731504625},
         *        TableProcessDwd(sourceTable=user_info, sourceType=insert, sinkTable=dwd_user_register, sinkColumns=id,login_name,nick_name,passwd,real_name,phone_num,email,head_img,user_level,birthday,gender,create_time,operate_time,status, op=r))
         *
         */
        //TODO 6.将流中数据写到kafka的不同主题中 ( topic=dwd_user_register)
        realDS.sinkTo(FlinkSinkUtil.getKafkaSink());

    }
}
